package com.atguigu.gmall.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.commont.Constant;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

/**
 * @Author lzc
 * @Date 2023/5/4 14:09
 */
public class DimUtil {
    
    public static JSONObject readDimFromPhoenix(Connection conn, String table, String id) {
        // 1. 拼接 sql
        String sql = "select * from " + table + " where id=?";
        List<JSONObject> list = JdbcUtil.queryList(conn, sql, new Object[]{id}, JSONObject.class);
        if (list.size() == 0) {
            throw new RuntimeException("没有查询到维度数据:" + table + "  " + id + ", 请检测 id 是否正确和维度表中是否有数据");
        }
        return list.get(0);
    }
    
    public static void main(String[] args) {
        System.out.println(readDimFromPhoenix(JdbcUtil.getPhoenixConnection(), "dim_sku_info", "1"));
    }
    
    // TODO
    public static JSONObject readDim(Jedis redisClient, Connection conn, String table, String id) {
        // 1. 先从 redis 读取维度
        JSONObject dim = readDimFromRedis(redisClient, table, id);
        // 2. 如果读到, 则直接返回
        if (dim == null) {
            // 3. 如果没有读到, 则从 phoenix 读取
            dim = readDimFromPhoenix(conn, table, id);
            // 4. 把读到的数据写入到 redis
            writeDimToRedis(redisClient, table, id, dim);
            System.out.println("从 数据库 读取到维度: " + table + " " + id);
            
        }else {
            System.out.println("从 缓存 读取到维度: " + table + " " + id);
        }
        return dim;
    }
    
    private static void writeDimToRedis(Jedis redisClient, String table, String id, JSONObject dim) {
        String key = getKey(table, id);
        /*redisClient.set(key, dim.toJSONString());  // 写入到 string
        redisClient.expire(key, Constant.TWO_DAYS);*/ // 设置 ttl
        redisClient.setex(key, Constant.TWO_DAYS, dim.toJSONString());  // 一次性的写入数据和设置 ttl
    }
    
    public static String getKey(String table, String id) {
        return table + ":" + id;
    }
    
    private static JSONObject readDimFromRedis(Jedis redisClient, String table, String id) {
        // string
        String key = getKey(table, id);
        String json = redisClient.get(key);
        if (json != null) {
            return JSON.parseObject(json);
        }
        return null;
    }
}
